import Router from "koa-router";
import db from './../database/connection.js'
import { tokenConfig, blackTokenList } from './../database/config.js'
import jwt from "jsonwebtoken";

const router = new Router();

// id 为可选参数
router.get("/:id?", (ctx, next) => {
    const userId = ctx.params.id;
    ctx.body = "routes/users.js --> get --> /" + `, 参数id:  ${userId}`;
});

/**
 * 登录
 * POST /login
 * @param {string} username 用户名
 * @param {string} password 密码
 * 测试代码见 test.html
 */
router.post("/login", async (ctx, next) => {
    const { username, password } = ctx.request.body;
    const sql = `SELECT * FROM users WHERE username = ?`;
    const [rows] = await db.execute(sql, [username]);
    if (rows.length) {
        const item = rows[0];
        if (item.password === password) {
            const { secret, expiresIn } = tokenConfig;
            const token = jwt.sign({ username }, secret, { expiresIn });
            ctx.body = {
                success: true,
                message: "登录成功",
                data: {
                    token
                }
            }
        } else {
            ctx.body = {
                success: false,
                message: "用户名或密码错误"
            }
        }
    } else {
        ctx.body = {
            success: false,
            message: "用户名未注册"
        }
    }
});

/**
 * 获取用户信息
 * POST /userInfo
 * 测试代码见 test.html
 */
router.post("/userInfo/:id?", async (ctx, next) => {
    const { authorization } = ctx.request.header;
    const _666 = ctx.params.id;
    if (!authorization) {
        ctx.body = {
            success: false,
            message: "缺少授权头"
        }
        return;
    }
    const token = authorization.split(' ')[1];
    if (!token) {
        ctx.body = {
            success: false,
            message: "请先登录"
        }
        return;
    }
    const { secret } = tokenConfig;
    const { username } = jwt.verify(token, secret);
    let item = null;
    if (_666 === '666') {
        const sql = `SELECT * FROM users`;
        const [rows] = await db.execute(sql, []);
        item = rows.map(o => {
            delete o.password;
            return o;
        })
    } else {
        const sql = `SELECT * FROM users WHERE username = ?`;
        const [rows] = await db.execute(sql, [username]);
        item = rows[0];
        delete item?.password;
    }
    if (item) {
        ctx.body = {
            success: true,
            message: "获取用户信息成功",
            data: item
        }
    } else {
        ctx.body = {
            success: false,
            message: "用户不存在"
        }
    }
});

/**
 * 登出
 * POST /logout
 * 测试代码见 test.html
 */
router.post("/logout", async (ctx, next) => {
    const { authorization } = ctx.request.header;
    if (!authorization) {
        ctx.body = {
            success: false,
            message: "缺少授权头"
        }
        return;
    }
    const token = authorization.split(' ')[1];
    if (!token) {
        ctx.body = {
            success: false,
            message: "请先登录"
        }
        return;
    }
    if (blackTokenList.has(token)) {
        ctx.body = {
            success: false,
            message: "该用户已登出"
        }
        return;
    } else {
        blackTokenList.add(token);
        ctx.body = {
            success: true,
            message: "退出登录成功",
            data: null
        }
    };
});

export default router;
